package com.qcxy.gzy.activity.base;

import android.app.Dialog;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.widget.Toast;

import com.google.gson.Gson;
import com.qcxy.gzy.bean.ComReceiveDataBean;
import com.qcxy.gzy.bean.SerialPortCommand;
import com.qcxy.gzy.view.dialog.SwitchEMDialog;
import com.qxcy.gzy.util.CRCChecker;
import com.qxcy.gzy.util.SerialPortUtils;

import java.util.Locale;
import java.util.Random;

public abstract class BaseSwitchActivity extends BaseAdaptiveActivity {
    public interface SwitchEMListener {
        /**
         * @param isSuccess 切换是否成功
         * @param message   切换信息
         * @param type      当前启动的电机
         */
        void onSwitch(boolean isSuccess, String message, @SerialPortUtils.ElectricMachineryType int type);
    }

    public interface BreakdownListener {
        /**
         * @param breakdownType 故障类型
         */
        void onBreakdown(String breakdownType);
    }

    //日志工具
    protected StringBuilder builder;
    //是否当前有命令正在执行
    protected boolean isCommandRun;
    //当前发送命令
    protected SerialPortCommand currentCommand;
    //自动重发线程
    protected autoResendThread resendThread;

    protected int status;
    //当前是否处于切换电机中
    protected boolean isEMSwitching = false;
    //命令失败重发次数
    protected int resendCount = 5;
    //读命令等待时间
    protected int readWaitTime = 10;

    protected boolean isImp() {
        Class<?> clazz = this.getClass();
        Class<?> aClass = SwitchEMListener.class;
        return aClass.isAssignableFrom(clazz);
    }

    protected boolean isBreakdownImp() {
        Class<?> clazz = this.getClass();
        Class<?> aClass = BreakdownListener.class;
        return aClass.isAssignableFrom(clazz);
    }

    protected void delayRun(Runnable runnable, int millis) {
        new BaseHandler(Looper.getMainLooper()).postDelayed(runnable, millis);
    }

    //命令自动重发线程
    public class autoResendThread implements Runnable {

        //线程控制
        private boolean mSendEndFlag;
        //当前命令执行次数
        private int currentSendCount;
        //当前命令
        private SerialPortCommand sendCommand;
        //命令间隔时间
        private int delay;

        public autoResendThread(SerialPortCommand sendCommand, int delay) {
            builder.append("启动命令发送线程").append("\n");
            builder.append(sendCommand.toString()).append("\n");
            this.mSendEndFlag = true;
            currentSendCount = 0;
            this.sendCommand = sendCommand;
            this.delay = delay;
        }

        @Override
        public void run() {
            try {
                int timeOutCommand = 0;
                builder.append("发送计数：");
                while (mSendEndFlag && currentSendCount < resendCount && sendCommand != null) {
                    if (isCommandRun) {
                        //当前命令正在执行
                        timeOutCommand++;
                    } else {
                        timeOutCommand = 0;
                    }
                    //自动解锁命令发送，防止一直未收到回复
                    if (timeOutCommand >= delay) {
                        timeOutCommand = 0;
                        isCommandRun = false;
                    }
                    if (!isCommandRun && mSendEndFlag) {
                        isCommandRun = true;
                        currentSendCount++;
                        builder.append(currentSendCount).append("---");
                        send(sendCommand.command);
                    }
                    if (mSendEndFlag) {
                        Thread.sleep(10);
                    }
                }
                if (currentSendCount == resendCount) {
                    //通讯故障
                    if (isBreakdownImp()) {
                        ((BreakdownListener) BaseSwitchActivity.this).onBreakdown("串口通讯故障");
                    }
                    if (isEMSwitching) {
                        if (isImp()) {
                            ((SwitchEMListener) BaseSwitchActivity.this).onSwitch(false, "串口通讯故障", runEMType);
                        }
                    }
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        //线程停止外部接口
        public synchronized void stopSend() {
            mSendEndFlag = false;
            currentSendCount = 0;
        }
    }

    //切换电机加载动画相关****************************************************************************
    protected static final int loading = 0x120;

    protected void showLoadingView() {
        isEMSwitching = true;
        showDialog(loading);
    }

    protected void hideLoadingView() {
        if (dialog != null && dialog.isShowing())
            dismissDialog(loading);
        isEMSwitching = false;
    }

    @Override
    protected Dialog onCreateDialog(int id) {
        if (id == loading && dialog == null) {
            dialog = new SwitchEMDialog(this);
            dialog.setCanceledOnTouchOutside(false);
            dialog.setCancelable(false);
            dialog.show();
        }
        return dialog;
    }

    private SwitchEMDialog dialog;


    //模拟串口***************************************************************************************
    protected static final int AppToast = 0x010;

    public class BaseHandler extends Handler {
        public BaseHandler(Looper looper) {
            super(looper);
        }

        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case AppToast:
                    String m = msg.obj.toString();
                    if (TextUtils.isEmpty(m)) return;
                    Toast.makeText(BaseSwitchActivity.this, m, Toast.LENGTH_SHORT).show();
                    break;
                default:
                    try {
                        ComReceiveDataBean bean = (ComReceiveDataBean) msg.obj;
                        if (bean != null)
                            onDataReceived(bean);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;
            }
        }
    }

    protected void toast(int message) {
        Message msg = new Message();
        msg.what = AppToast;
        msg.obj = getResources().getString(message);
        new BaseHandler(Looper.getMainLooper()).sendMessage(msg);
    }

    protected void toast(String message) {
        Message msg = new Message();
        msg.what = AppToast;
        msg.obj = message;
        new BaseHandler(Looper.getMainLooper()).sendMessage(msg);
    }

    protected void localSendMessage(byte[] result) {
        Message message = new Message();
        message.what = 0x001;
        message.obj = new ComReceiveDataBean(result, result.length);
        new BaseHandler(Looper.getMainLooper()).sendMessage(message);
    }

    protected void sendTest(final byte[] bOutArray) {
        wBase(json(bOutArray));
        if (getSerialResult()) {
            byte add = bOutArray[0];//从机地址
            byte type = bOutArray[1];//读或者写
            byte address01 = bOutArray[2];//（读：寄存器地址1，写：写地址1）
            byte address02 = bOutArray[3];//（读：寄存器地址2，写：写地址2）
            byte data = bOutArray[5];//动作类型（打开或者关闭）
            if (address01 == 0x00) {
                switch (address02) {
                    case SerialPortUtils.addressDistance: {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                new Handler().postDelayed(new Runnable() {
                                    @Override
                                    public void run() {
                                        byte emAddress = runEMType == SerialPortUtils.ElectricMachineryBig ?
                                                SerialPortUtils.addressBrakeBig : SerialPortUtils.addressBrakeSmall;
                                        byte[] x = SerialPortUtils.intToByteArray(getSerialResult(2500));
                                        byte[] result = CRCChecker.getSendBuf(new byte[]{emAddress, 0x03, 0x02, x[2], x[3], 0x00, 0x00});
                                        wBase("读运动距离");
                                        localSendMessage(result);
                                    }
                                }, 200);
                            }
                        });
                    }
                    break;
                    case SerialPortUtils.addressSC:
                        w("刹车（启动或者停止）操作返回");
                        localSendMessage(bOutArray);
                        break;
                    case SerialPortUtils.brakeStatusBig:
                        if (type == SerialPortUtils.typeRead) {
                            byte brake = getSerialResult() ? (byte) 0x01 : (byte) 0x00;
                            //读制动器类型
                            byte[] result = CRCChecker.getSendBuf(new byte[]{0x02, 0x03, 0x02, 0x00, brake, 0x00, 0x00});
                            w("读制动器2返回");
                            localSendMessage(result);
                        } else {
                            //写制动器类型
                            w("写制动器2返回");
                            localSendMessage(bOutArray);
                        }
                        break;
                    case SerialPortUtils.brakeStatusSmall:
                        if (type == SerialPortUtils.typeRead) {
                            byte brake = getSerialResult() ? (byte) 0x01 : (byte) 0x00;
                            //读制动器类型
                            byte[] result = CRCChecker.getSendBuf(new byte[]{0x02, 0x03, 0x01, 0x00, brake, 0x00, 0x00});
                            w("读制动器1返回");
                            localSendMessage(result);
                        } else {
                            //写制动器类型
                            w("写制动器1返回");
                            localSendMessage(bOutArray);
                        }
                        break;
                    case SerialPortUtils.addressEMControl:
                        if (data == 0x01) {
                            //启动电机
                            w("写启动电机返回");
                            localSendMessage(bOutArray);
                        } else {
                            //停止电机
                            w("写停止电机返回");
                            localSendMessage(bOutArray);
                        }
                        break;
                    case SerialPortUtils.addressEMStatus:
                        byte emStatus = getSerialResult() ? (byte) 0x04 : (byte) 0x08;
                        byte emAddress = runEMType == SerialPortUtils.ElectricMachineryBig ?
                                SerialPortUtils.addressBrakeBig : SerialPortUtils.addressBrakeSmall;
                        //读电机状态
                        byte[] result = CRCChecker.getSendBuf(new byte[]{emAddress, 0x03, 0x02, 0x00, emStatus, 0x00, 0x00});
                        w("读电机返回");
                        localSendMessage(result);
                        break;
                }
            } else {
                if (address02 == SerialPortUtils.addressPower[1]) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            //设置力量
                            new Handler().postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    wBase("设置力量操作返回");
                                    localSendMessage(bOutArray);
                                }
                            }, 200);

                        }
                    });
                }
            }
        } else {
            wBase("串口无返回值");
        }
    }

    protected boolean getSerialResult() {
        Random random = new Random();
        return random.nextInt(10) > 1;
    }

    protected int getSerialResult(int max) {
        Random random = new Random();
        return random.nextInt(max);
    }

    protected String json(Object obj) {
        return new Gson().toJson(obj);
    }

    protected void w(String message) {
        System.out.println("正在处于切换电机状态：" + status + "--------------------" + message);
    }

    protected void wBase(String message) {
        System.out.println("动作状态：--------------------" + message);
    }

    protected void builderW(String tag) {
        builder.append(String.format(Locale.CHINA, "%s------------------------------------------------------------------------\n", tag));
        SerialPortUtils.saveLocalDailyLog(builder.toString());
        builder.delete(0, builder.length());
    }
}